--
-- Author: bin.zhao
-- Date: 2018-06-15 11:31:42
--
-- JewelView
--
local TabsBtn = require("app.widget.TabsBtn")
local Jewel = require("app.public.dao.Jewel")
local JewelRender = import(".renders.JewelRender")
local IconRender = require("app.widget.renders.IconRender")
local ListViewVertical = require("app.widget.listview.ListViewVertical")
local Armature = require("app.public.avatar.Armature")

local JewelTransformPanel = import(".JewelTransformPanel")

local SEARCH_CD = 0.5
local expBarBgZOrder = 0 -- 宝石经验条Bg Zorder
local fileName = string.getModeName(...)
local JewelView = class(fileName, app.mvc.ViewBase)

local CCNode_setVisible = cc.Node.setVisible

function JewelView:createArmature(armaturedir,armatureName,actionName ,needClear)
    -- print("##############   createArmature   ",armatureName,"      ",actionName)
    local node = Armature.create({path=armaturedir,armatureName=armatureName,animationName="",skeletonName=armatureName})
    local function callback ()
        executeFunc(self._onOperate,"endActionClear")
    end
    if needClear and needClear == true then
        node:play(actionName,1,callback)
    else
        node:play(actionName,1)
    end
    return node
end

JewelView.VIEW_ROOT_RES = Res.JewelUi
function JewelView:init()
    self.mUINode = self._root
    self:initSceneNode()
    self:initEquipNode()
    self:initJewelNode()
    self:initCostInfo()

    self:updateComposeCost(0)
    self.renderNode = {}
    self:checkGuide()

    self.showConfirmCompose = false
end

function JewelView:show(index)
    self.super.show(self)
    self:switchPanel(index)
end

function JewelView:onOperate(cb)
    self.super.onOperate(self, cb)

    self._transformPanel:onOperate(cb)
end

function JewelView:onSwitchPanel(cb)
    self._onSwitchPanel = cb
end

-- 检查是否触发了引导
function JewelView:checkGuide()
    local funcId = -1
    if self.equipNode:isVisible() then
        funcId = Constant.FUNC_TYPE_JEWEL
    elseif self.upgradeNode:isVisible() then
        funcId = Constant.FUNC_TYPE_JEWEL_STRENGTH
    end
    local params = {
        scene = funcId,
        sceneSelf = self,
        getFunc = self.getGuideNodeFunc,
        nextFunc = self.checkGuide
    }
    EM:notify("checkGuide", params)
end

-- 获取引导node
function JewelView:getGuideNodeFunc(id)
    if id == 148 then
        return self.slotNode[1]
    elseif id == 150 then
        -- local children = self.bagScrollView:getChildren()
        -- if 0 < #children then
        --     return children[1]
        -- end
        return self.bagScrollView:getCellByIndex(1)
    elseif id == 151 then
        return self.btnInlay
    elseif id == 152 then
        return self.btn_sj
    -- elseif id == 154 then
    --     return self._jewelChipIcon
    end
end

function JewelView:updateRedPoint(inlay)
    self.mUINode:findChild("Panel/Panel_tab/selected_btn_1/dot"):setVisible(inlay)
end

function JewelView:initSceneNode()
    self.panelBG = self.mUINode:findChild("Panel/Panel_bg")
    --装备镶嵌根节点
    self.equipNode = self.mUINode:findChild("Panel/set")
    self.equipNode:setVisible(true)
    --宝石升级根节点
    self.upgradeNode = self.mUINode:findChild("Panel/up")
    self.upgradeNode:setVisible(false)
    --装备空白
    self.blankNode = self.mUINode:findChild("Panel/blank")
    self.blankNode:setVisible(false)

    -- 宝石炼金
    self._transformPanel = JewelTransformPanel.create(self.mUINode:findChild("Panel/alchemy"))
    self._transformPanel:setVisible(false)

    --退出
    self.mUINode:findChild("Panel/Button_close"):addClickEventListener(function()
                executeFunc(self._onCloseView)
        end)

    local panelTab = self.mUINode:findChild("Panel/Panel_tab")
     -- 标签页初始化
    self.btn_sj = panelTab:findChild("selected_btn_2")
    local btns = {0,0,0}
    for i=1,3 do
        btns[i] = panelTab:findChild("selected_btn_".. i)
    end
    local binds = {self.equipNode, self.upgradeNode, self._transformPanel}

    local function onTabsBtn(index)
        if self.curIdx then
            self.curIdx = index
            self:switchPanel()
        else
            self.curIdx = index
        end
    end
    self.tabsBtn = TabsBtn.new(btns, onTabsBtn, 1, binds)
    
    if not UIHandler:isFunctionOpen(Constant.FUNC_TYPE_JEWEL_TRANSFORM) then
        self.tabBtn:getBtn(3):setVisible(false)
    end
end

function JewelView:getTransformPanel()
    return self._transformPanel
end

--刷新当前合成 需花费
function JewelView:updateComposeCost(costGold)
    local ownDust = UD:getMagicDust()
    self.moneyOwnText:setString(tostring(ownDust))
    self.composeCost:setString(costGold)--.."/"..ownDust)
    if costGold > ownDust then
        self.composeCost:setColor(cc.c3b( 255, 0, 0 ))
    else
        self.composeCost:setColor(cc.c3b( 255, 225, 132 ))
    end

end

function JewelView:initCostInfo()

    local moneyPanel = self.upgradeNode:findChild("Panel/Panel_money")
    moneyPanel:setTouchEnabled(true)
    moneyPanel:addTouchEventListener(function(sender,eventType)
        if eventType == ccui.TouchEventType.ended then
            local param = {itemId = 92,tipsType = Enums.TipsType.daibi}
            local boundingBoxTemp = sender:getBoundingBox()
            local worldPosTemp = sender:getParent():convertToWorldSpace( cc.p( boundingBoxTemp.x, boundingBoxTemp.y ) )
            boundingBoxTemp.x = worldPosTemp.x
            boundingBoxTemp.y = worldPosTemp.y
            param.boundingBox = boundingBoxTemp
            app:dispatchCustomEvent("EVENT_OPEN_FLOAT", {params = param})
        end
    end)
    self.moneyOwnText = moneyPanel:findChild("num")
    local moneyIcon = moneyPanel:findChild("icon")

    local coinConfig = GD:getCoinConfig( Enums.PropType.coinRes92 )
    local iconPath = GD:getImagePath(Res.coinIconPath,coinConfig.icon)
    moneyIcon:loadTexture( iconPath )

    self.composeCost = self.jewelUpRight:findChild("Panel_enter/power/num_gold")
    local costIcon = self.jewelUpRight:findChild("Panel_enter/power/power")
    local bigIconPath = GD:getImagePath(Res.coinIconPath,coinConfig.bigicon)
    costIcon:loadTexture( bigIconPath )
end

function JewelView:showNoJewelTip( isShow)
    self.upgradeNode:findChild("Panel/tips/text"):setVisible(isShow)
end

-- function JewelView:getJewelRenderByUid(uid)
--     for k,v in pairs(self.jewelScrollView:getChildren()) do
--         local renderData = v:getData()
--         if renderData then
--             local uidtem = renderData:getUid()
--             -- print("##########  getJewelRenderByUid    ",uid)
--             if uid == uidtem then
--                 return v 
--             end
--         end
--     end
--     return nil
-- end

function JewelView:refreshListClickStatus(jewelUid)
    self.jewelScrollView:foreachCellModels(function(cellModel, data)
        if cellModel.cell then
            cellModel.cell:setSelected(data:getUid() == jewelUid)
        else
            cellModel:setUIState("selected", data:getUid() == jewelUid)
        end
    end)
end

function JewelView:refreshJewelList( data ,jewelUid, isShowInlay)
    self.btnShowInlay:setBright(not isShowInlay)

    local function renderClick(sender)
        AM.playClickItemSound()
        executeFunc(self._onOperate,"clickJewel",sender:getData())
    end

    -- local function loadComplete(sender)
    --     local renders = self.jewelScrollView:getChildren()
    --     if renders then
    --         if jewelUid == nil then
    --             renderClick(renders[1])
    --         end
    --         self.renderNode = {}
    --         for k,v in pairs(renders) do
    --             local data = v:getData()
    --             if data then
    --                 local uid = data:getUid()
    --                 self.renderNode[uid] = v
    --             end
    --         end
    --     end
    --     executeFunc(self._onOperate,"refreshRender")
    -- end

    -- local function loadCompleteSingl(sender)
    --     sender:setMaskVisible(false)
    --     local senderData = sender:getData()
    --     if senderData and jewelUid then
    --         if senderData:getUid() == jewelUid then
    --             renderClick(sender)
    --         end
    --     end
    -- end

    local tipsEmpty = self.upgradeNode:findChild("Panel/Panel_tips")
    --默认底部都看不到
    self.panelInfo:setVisible(false)
    if data == nil or table.nums(data) < 1 then
        tipsEmpty:setVisible(true)
        self.jewelScrollView:setVisible(false)
    else
        tipsEmpty:setVisible(false)
        self.jewelScrollView:reloadData(data)--(data,0,renderClick,loadComplete,loadCompleteSingl)

        if jewelUid == nil then
            local cellData = self.jewelScrollView:getDataByIndex(1)
            if cellData then
                executeFunc(self._onOperate,"clickJewel",cellData)
            end
        else
            self.jewelScrollView:foreachCellModels(function(cellModel, cellData)
                if cellData.uid == jewelUid then
                    executeFunc(self._onOperate,"clickJewel",cellData)
                    return
                end
            end)
        end
        self.jewelScrollView:setVisible(true)
    end
end


function JewelView:disableJewelDark(jewelData)
    self.jewelScrollView:foreachCellModels(function(cellModel, data)
        local isVisible = false
        if jewelData and jewelData[data:getUid()] then
            isVisible = true
        end
        if cellModel.cell then
            cellModel.cell:setMaskVisible(isVisible)
        else
            cellModel:setUIState("mask", isVisible)
        end
    end)
end

--宝石合成 已选过的宝石 状态
function JewelView:refreshJewelRenderStatus(chooseTable)
    self.jewelScrollView:foreachCellModels(function(cellModel, data)
        local isVisible = false
        if chooseTable and chooseTable[data:getUid()] then
            isVisible = true
        end
        if cellModel.cell then
            cellModel.cell:setChooseToCompose(isVisible)
        else
            cellModel:setUIState("chooseToCompose", isVisible)
        end
    end)
end

--刷新合成选中宝石界面
function JewelView:refreshJewelComposePanel(jewel,posIndex,isShow)
    local rootIcon = self.composeIcon[posIndex]
    if not cc.isDead(rootIcon) then
        if isShow then
            rootIcon:setData(jewel)
            CCNode_setVisible(rootIcon,true)
            self:addAniToNode("jewelcompose"..tostring(posIndex), rootIcon)
        else
            CCNode_setVisible(rootIcon,false)
        end
    end
    self:refreshSliderAction(self.sliderNode[posIndex],isShow)
end

function JewelView:composeEffectCenter()
    local actionNode = self.composeResultIcon:getChildByName("actionComposeEffect")
    if actionNode then
        actionNode:removeFromParent()
    end
    actionNode = self:createArmature(Res.JewelComposeArmatureCenter,"fenjie2", "fenjie2")
    actionNode:setName("actionComposeEffect")
    local sizeIcon = self.composeResultIcon:getContentSize()
    actionNode:setPosition(cc.p(sizeIcon.width/2,sizeIcon.height/2))
    self.composeResultIcon:addChild(actionNode)
    local panel_icon = self.jewelUpRight:findChild("Panel_icon")
    for i,v in ipairs(self.composeIcon) do
        local action = self:createArmature(Res.JewelComposeArmatureRound,"fenjie1", "fenjie1")
        local sizetem = v:getContentSize()
        local posX = v:getPositionX()
        local posY = v:getPositionY()
        action:setPosition(cc.p(posX + sizetem.width/2,posY + sizetem.height/2))
        panel_icon:addChild(action)
    end
    executeFunc(self._onOperate,"endActionClear")

end


-- isfull true从0到100。 false 从100 到 0
function JewelView:refreshSliderAction(sliderNode,isFull)
    -- print("#########    滑块。 ",isFull)
    local slider  = sliderNode:findChild("Panel/Slider")
    local iamge = sliderNode:findChild("Panel/Image_light")
    
    if isFull == false then 
        slider:setPercent(0)
        slider:setVisible(false)
        iamge:setVisible(false)
        sliderNode:stopAllActions()
    else
        iamge:setVisible(true)
        slider:setVisible(true)
        slider:setPercent(0)
        local percent = 0
        local function playAction()
            percent = percent+10
            if percent > 100 then
                sliderNode:stopAllActions()
                return
            end
            slider:setPercent(percent)
        end
        local actions = {}
        table.insert(actions, cc.CallFunc:create(playAction))
        table.insert(actions, cc.FadeOut:create(0.02))
        sliderNode:runAction(cc.RepeatForever:create(cc.Sequence:create(actions)))
    end
end

--刷新将要合成的宝石 
-- 1 没有宝石。 
--showType  1 不确定 2 确定 。3 已合成的宝石
--isfull  是否放满3个宝石
function JewelView:refreshComposeResult(jewel,showType,isFull)
    local opacityFull, opacityHalf = 255 , 160
    local rootIcon = self.composeResultIcon
    if jewel == nil then
        rootIcon:setVisible(false)
        return
    end
    rootIcon:setVisible(true)
    local iconNode = rootIcon:findChild("Panel/icon")
    local unKnow = rootIcon:findChild("Panel/img_unknown")
    self.showConfirmCompose = not (showType == 1)
    if showType == 2 or showType ==1 then
        local tid = jewel.tid + 1
        local itemData = Jewel.new()
        itemData:read({tid=tid})  
        rootIcon:setData(itemData) 
    elseif showType == 3 then
        rootIcon:setData(jewel) 
    end

    CCNode_setVisible(unKnow,(showType == 1))
    CCNode_setVisible(iconNode,not (showType == 1))

    rootIcon:setTipEnable( self.showConfirmCompose )
    --组合的 半透明处理
    if isFull == true then
        iconNode:setOpacity(opacityFull)
        unKnow:setOpacity(opacityFull)
        self.jewelBgHight:setVisible(true)
    else
        iconNode:setOpacity(opacityHalf)
        unKnow:setOpacity(opacityHalf)
        self.jewelBgHight:setVisible(false)
    end
end

function JewelView:changeChooseBtn(isChoose)
    self.chooseJewelBtn:setVisible(isChoose)
    self.concelBtn:setVisible(not isChoose)
end

function JewelView:setCanCompose(binlay, cancompose, l)
    self.needTips:setVisible(false)
    if cancompose == false then --等级不够
        self.needTips:setString(string.format(L("jewel_compose_needlv"), tostring(l)))
        self.needTips:setVisible(true)
    elseif binlay then --已镶嵌
        self.needTips:setString(L("jewel_compose_already_inlay"))
        self.needTips:setVisible(true)
    end
end

function JewelView:initJewelNode()
    self.jewelBG            = self.upgradeNode:findChild("Panel/Panel_frame")
    self.jewelUpRight       = self.upgradeNode:findChild("Panel/Panel_right")
    self.jewelUpLeft        = self.upgradeNode:findChild("Panel/Panel_left")
    self.jewelUpNoJewel     = self.upgradeNode:findChild("Panel/tips_j")          -- 没有可供吞噬的宝石
    self.jewelUpNoEquips    = self.upgradeNode:findChild("Panel/tips")            -- 没有可以升级的宝石
    self.notConfirmTip         = self.upgradeNode:findChild("Panel/icon_tips")
    display.nodeRemoveForNotHit(self.notConfirmTip, function()
        self:tipsCannotConfirmJewel(false)
        self.composeResultIcon:setSelected(false)
    end)
    --宝石列表

    local params = {
		renderClass = IconRender,
        perNum = 4,
        gapY = 6,
        isMultipleLayer = true,
		cellEventProxy = function(eventName, render)
			AM.playClickItemSound()
            executeFunc(self._onOperate,"clickJewel",render:getData())
            
            local selected = app:sendMsg("JewelController", "isRepeatClickJewel", render:getData()) 
            local check = app:sendMsg("JewelController", "canAddChooseJewel", render:getData())
            if selected == false and check ~= 2 then
                executeFunc(self._onOperate, "chooseJewelToCompose")
            end

            if selected then
                executeFunc(self._onOperate, "concelChooseJewel")
            end
		end,
    }
    local jewelScrollview = self.jewelUpLeft:findChild("ScrollView")
    self.jewelScrollView = ListViewVertical.new(jewelScrollview , params )
    --宝石品质标签
    local temQualityTab     = self.jewelUpLeft:findChild("Panel_top")
    executeFunc( self._onOperate, "jewelTabChoose",{selectIndex = 4})
    --仅显示已镶嵌
    self.btnShowInlay = self.jewelUpLeft:findChild("Button_tick")
    self.btnShowInlay:setEnabled(true)
    self.btnShowInlay:addClickEventListener(
        function()
            local isBright = self.btnShowInlay:isBright()
            self.btnShowInlay:setBright(not isBright)
            executeFunc(self._onOperate, "refreshComposeJewel", isBright)
        end
    )

    --当前选中宝石信息
    self.panelInfo  = self.jewelUpLeft:findChild("Panel_bom")
    self.jewelIcon  = IconRender.create(self.panelInfo:findChild("icon"))
    self.iconTips   = self.panelInfo:findChild("tips")

    self.midSelIcons = {}
    for i = 1, 6 do
        local icon = self.panelInfo:findChild("icon"..tostring(i))
        table.insert(self.midSelIcons, icon)
        icon:hide()
    end

    local recommendNode = self.panelInfo:findChild("Text_recommend")
    CCNode_setVisible(recommendNode,false)
    --选择按钮
    self.chooseJewelBtn = self.panelInfo:findChild("Button_change")
    self.chooseJewelBtn:setVisible(false)
    --取消按钮
    self.concelBtn = self.panelInfo:findChild("Button_quxiao")
    self.concelBtn:setVisible(false)

    self.chooseJewelBtn:addClickEventListener(function()
            executeFunc(self._onOperate, "chooseJewelToCompose")
        end)
    self.concelBtn:addClickEventListener(function()
            executeFunc(self._onOperate, "concelChooseJewel")
        end)

    local costImg    = self.jewelUpRight:findChild("Panel_enter/power/power")
    -- self.jewelUpRight:findChild("Panel_enter/power"):hide()

    self.needTips = self.jewelUpRight:findChild("tips")
    self.needTips:hide()

    --合成按钮
    self.composeBtn = self.jewelUpRight:findChild("Panel_enter/Button_enter")
    self.composeBtn:setBright(false)
    self.composeBtn:setTouchEnabled(false)
    self.composeBtn:addClickEventListener(function()
            executeFunc(self._onOperate, "composeJewel")
        end)
    --选中合成宝石icon
    self.composeIcon = {}
    self.sliderNode = {}
    for i=1 ,3 do
        self.composeIcon[i] = IconRender.create(self.jewelUpRight:findChild("Panel_icon/icon_"..i))
        CCNode_setVisible(self.composeIcon[i],false)
        self.composeIcon[i]:setClickHandler(function()
                executeFunc(self._onOperate, "selectChooseJewel",i)
                executeFunc(self._onOperate, "concelChooseJewel")
            end)
        self.sliderNode[i] = self.jewelUpRight:findChild("Panel_icon/bg_"..i)
        self.sliderNode[i]:setVisible(true)
        local slider  = self.sliderNode[i]:findChild("Panel/Slider")
        local iamge   = self.sliderNode[i]:findChild("Panel/Image_light")
        slider:setVisible(false)
        iamge:setVisible(false)
    end
    self.jewelBgHight = self.jewelUpRight:findChild("Panel_icon/Image_light")
    self.jewelBgHight:setVisible(false)

    self.composeResultIcon = IconRender.create(self.jewelUpRight:findChild("Panel_icon/icon"))
    self.composeResultIcon:setClickHandler(function()
            if self.showConfirmCompose == false then
                executeFunc(self._onOperate, "composeJewelClick")
            end
        end)

    self.composeResultIcon:setTipEnable(true)
    CCNode_setVisible(self.composeResultIcon,false)    
end

function JewelView:tipsCannotConfirmJewel(isShow)
    self.notConfirmTip:setVisible(isShow)
    local textTip = self.notConfirmTip:findChild("Panel/text")
    textTip:setString(L("jewel_randomtips"))
end

function JewelView:refreshRightJewelClickStatus(pos)
    for i = 1, 3 do
        self.composeIcon[i]:setSelected(pos == i)
    end
end

function JewelView:clearForUpgrade(isClearComposeJewel)

    local showCompose = isClearComposeJewel
    if showCompose== nil then
        showCompose = false
    end

    -- print("宝石合成成功。 清空合成界面")
    for i=1 ,3 do
        CCNode_setVisible(self.composeIcon[i],false)
    end

    self.composeResultIcon:setVisible(not showCompose)
    self.jewelBgHight:setVisible(not showCompose)
    for i,v in ipairs(self.sliderNode) do
        self:refreshSliderAction(v,false)
    end
    self:refreshComposeBtn(false)
end

--设置合成按钮状态
function JewelView:refreshComposeBtn(isBright)
    self.composeBtn:setBright(isBright)
    self.composeBtn:setTouchEnabled(isBright)

    self.composeName = self.composeBtn:findChild("name")
    if isBright then
        self.composeName:enableOutline(cc.c4b(0,0,0,255),1)
        self.composeName:setTextColor(cc.c3b( 255, 255, 255))
    else
        self.composeName:enableOutline(cc.c4b(75,71,63,255), 1)
        self.composeName:setTextColor(cc.c3b( 201,193,175))
     end
end

-- isBright  是否高亮。  isChoose 是否改变功能 true。“选择”。 false “取消选择”
function JewelView:refreshChooseBtnStatus(fontName)
    local nameText = self.chooseJewelBtn:findChild("name")
    nameText:setString(fontName)
end

--宝石描述信息
function JewelView:refreshBottomJewelInfo( jewel )

    local jewelName = self.panelInfo:findChild("Text_name")
    local propertyText = self.panelInfo:findChild("num")
    local posTip = self.panelInfo:findChild("tips")
    local nameBg = self.panelInfo:findChild("bg_name")
    
    if jewel then
        self.panelInfo:setVisible(true)
        --宝石描述信息
        jewelName:setString(jewel:getName(true))
        local color = Enums.QualityColor[jewel.quality]
        if color then
            jewelName:setTextColor(color)
        end
        self.jewelIcon:setData(jewel)
        --属性信息
        local attrName, attrNum = UD:formatAttr( jewel:getAttrType(), jewel:getAttrVal() )
        propertyText:setString(table.concat( { attrName, attrNum } ))
        -- --可装备位置
        posTip:setString(L(jewel.pos))
    else
        self.panelInfo:setVisible(false)
    end
end

function JewelView:initEquipNode()
    self.equipBG            = self.equipNode:findChild( "Panel/Panel_frame" )
    self.equipRightPanel    = self.equipNode:findChild( "Panel/Panel_right" )
    self.equipTipNoJewel    = self.equipNode:findChild( "Panel/tips_j" )   -- 没有宝石
    self.equipTipNoEquip    = self.equipNode:findChild( "Panel/tips" )    -- 没有装备
    self.equipJewelStar          = self.equipNode:findChild( "Panel/bg_star" )
    self.equipNode:findChild("Panel/ScrollView"):setVisible( false )
    self.equipNode:findChild("Panel/star_num"):setString(string.format(L("jewel_master_string2"),UD:getCurEquipedJewelScore()))
    self.m_EquipInfoNode=self.equipNode:findChild("Panel/Panel_mid")
    self.m_EquipInfoNode:setVisible(false)
    --孔
    self.slotNode = {}
    self.slotPos = {}
    for i=1,4 do
        self.slotNode[i] = self.m_EquipInfoNode:getChildByName("jewel_"..i)
        local posX ,posY = self.slotNode[i]:getPosition()
        self.slotPos[i] = cc.p(posX,posY)
    end

    self.equipJewelStar:setTouchEnabled(true)
    self.equipJewelStar:addClickEventListener(function()
        executeFunc(self._onOperate,"showJewelStarView")
    end)

    --list列表注册加载函数
    -- local createRenderBase = function(list,idx)
    --         local items = list:getItems()
    --         local render = items[idx]
    --         if nil == render then
    --             render = JewelRender.create()
    --             list:pushBackCustomItem(render)
    --         end
    --         render:setVisible(true)
    --         return render
    --     end
    -- self.equipListView   = self.equipNode:findChild("Panel/ListView")
    -- self.equipListView.createRender   = createRenderBase
    local params = {
		renderClass = JewelRender,
        cellEventProxy = function(eventName, cellModel)
			executeFunc(self._onOperate,"selectBtn",cellModel:getIndex())
		end,
	}
    self.equipListView = ListViewVertical.new( self._ui["Panel/ListView"], params )
    
   
    self._equipInfoIcon = IconRender.create( self.m_EquipInfoNode:findChild("icon") )
    self._equipInfoIcon:setTipEnable( true )

    self.m_EquipInfoNode.nameNode=self.m_EquipInfoNode:getChildByName("name")
    self.equipInfoDec = self.m_EquipInfoNode:getChildByName("tips")
    --孔信息

    self._CurSlotNodeBg=self.m_EquipInfoNode:findChild("Panel_bom/bg")

    self._CurSlotNode=self.m_EquipInfoNode:findChild("Panel_bom/icon")

    self._CurSlotTips=self.m_EquipInfoNode:findChild("Panel_bom/Text_tips")
    self.m_EquipInfoNode:findChild("Panel_bom/tips_1"):setVisible(false)
    self.slotJewelPosTip = self.m_EquipInfoNode:findChild("Panel_bom/tips")
    CCNode_setVisible(self.slotJewelPosTip,false)

    self.midEquipSelIcons = {}
    for i = 1, 6 do
        local icon = self.m_EquipInfoNode:findChild("Panel_bom/icon"..tostring(i))
        table.insert(self.midEquipSelIcons, icon)
        icon:hide()
    end

    self._CurSlotTips:setVisible(false)
    self._CurSlotName=self.m_EquipInfoNode:findChild("Panel_bom/Text_name")

    self._CurSlotPropNum=self.m_EquipInfoNode:findChild("Panel_bom/num")

    self._CurSlotButton_up=self.m_EquipInfoNode:findChild("Panel_bom/Button_up")

    self._CurSlotButton_unload=self.m_EquipInfoNode:findChild("Panel_bom/Button_unload")
    self._CurSlotButton_unload:setVisible(false)
    self._CurSlotButton_unload:addClickEventListener(function()
        -- print("_CurSlotButton_unload click")
        if self.mCurEquip and self.mCurEquip.jewelSlots and self.mCurEquip.jewelSlots[self.mCurSlotIndex] then
            EM:notify("EVENT_UNEQUIP_JEWEL",{equipUid=self.mCurEquip.uid,slotIndex=self.mCurSlotIndex})
        end
    end)

    local bagScrollparams = {
		renderClass = IconRender,
        perNum = 4,
        gapY = 6,
        isMultipleLayer = true,
        cellEventProxy = function(eventName, render)
            AM.playClickItemSound()
            self:_clickRightBagScrollView(render:getData())
		end,
    }
    local bagScrollview = self.equipNode:findChild("Panel/Panel_right/ScrollView")
    self.bagScrollView = ListViewVertical.new(bagScrollview , bagScrollparams )                           

    self.bagDetailPanel=self.equipNode:findChild("Panel/Panel_right/Panel_bom")
    self.bagDetailPanel:setVisible(false)

    self.rightBagSelIcons = {}
    for i = 1, 6 do
        local icon = self.equipNode:findChild("Panel/Panel_right/Panel_bom/icon"..tostring(i))
        table.insert(self.rightBagSelIcons, icon)
        icon:hide()
    end

    --背包宝石信息
    self._CurJewelNode=self.bagDetailPanel:findChild("icon")

    self._CurJewelRecommend=self.bagDetailPanel:findChild("Text_recommend")

    self._CurJewelRecommend:setVisible(false)
    self.bagDetailPanel:findChild("Text_tips"):setVisible(false)

    self._CurJewelName=self.bagDetailPanel:findChild("Text_name")

    self._CurJewelPropNum=self.bagDetailPanel:findChild("num")

    --镶嵌按钮
    self.btnInlay=self.bagDetailPanel:findChild("Button_change")
    self.btnGotoInlay=self.bagDetailPanel:findChild("Button_change_1")

    self.btnGotoInlay:addClickEventListener(function(sender)
        app:sendMsg("JewelController", "gotoInlayByJuid", nil, self.mCurJewel.uid)
    end)

    self.btnInlay:addClickEventListener(function()
        -- if self.isgotoinlay then
        --     app:sendMsg("JewelController", "gotoInlayByJuid", nil, self.mCurJewel.uid)
        --     return 
        -- end
        self:equipJewel()
        display.setBtnTouchEnable( self.btnInlay, false)
        self.btnInlay:performWithDelay(function()
                display.setBtnTouchEnable(self.btnInlay, true)
            end, SEARCH_CD)
    end)

    self.tipRightJewelType = self.bagDetailPanel:findChild("tips_1")
    CCNode_setVisible(self.tipRightJewelType ,false)
    self.tipRightJewelPos = self.bagDetailPanel:findChild("tips")
    CCNode_setVisible(self.tipRightJewelPos ,false)
end

--切换界面
function JewelView:switchPanel(idx)
    if idx then
        self.curIdx = idx
        self.tabsBtn:setSelected(self.curIdx)
    else
        executeFunc(self._onSwitchPanel, self.curIdx)
    end

    -- 宝石转换的动画
    self._transformPanel:playAction(self.curIdx == 3)

    -- 非镶嵌界面，没装备提示不显示
    if self.curIdx ~= 1 then
        self.blankNode:setVisible(false)
    end

    self:checkGuide()
end

--镶嵌宝石
function JewelView:equipJewel()
    if self.mCurJewel and self.mCurEquip and self.mCurSlotIndex then

        if not self.mCurJewel or not self.mCurEquip.jewelSlots or not self.mCurEquip.jewelSlots[self.mCurSlotIndex] then
            app:popMessage("setjewelfail")
            return
        else
            if not self.mCurEquip.jewelSlots[self.mCurSlotIndex]:fitJewel(self.mCurJewel) then
                app:popMessage("setjewelfail")
                return
            end
        end

        local needConfirm=false
        if self.mCurEquip and self.mCurEquip.bindType ==2 and not self.mCurEquip:isBind() then
            needConfirm=true
        end
        if self.mCurJewel and self.mCurJewel.bindType==2 and not self.mCurJewel:isBind() then
            needConfirm=true
        end

        local function okFunc()
            if self.mCurEquip and self.mCurJewel then
                EM:notify("EVENT_EQUIP_JEWEL",{equipUid=self.mCurEquip.uid,slotIndex=self.mCurSlotIndex,jewelUid=self.mCurJewel.uid})
            end
        end

        if needConfirm then
            app:popMessage("jewelbindingconfirm", nil, {ok=okFunc})
        else
            okFunc()
        end
    end
end

function JewelView:showEquipInfo(tag,slotIndex)
    local oldCurEquip = self.mCurEquip
    self.mCurEquip=self.equipList[tag]

    if slotIndex then
        self.mCurSlotIndex = slotIndex 
    else
        if not (oldCurEquip and oldCurEquip.uid == self.mCurEquip.uid and
                self.mCurSlotIndex and 
                #self.mCurEquip.jewelSlots >= self.mCurSlotIndex) then
            self.mCurSlotIndex=1
        end
    end
    
    local tid = self.mCurEquip:getId()
    local conf = GD:getEquipConf(tid)
    self.equipInfoDec:setString(string.format( L("jewel_weapon_info"),
        conf.lv,L(tostring(conf.locationtext))
            ))

    if self.mCurEquip then
        self.curEquipUid=self.mCurEquip.uid
        self.m_EquipInfoNode:setVisible(true)
    else
        self.m_EquipInfoNode:setVisible(false)
        return
    end

    self._equipInfoIcon:setData(self.mCurEquip)

    self.m_EquipInfoNode.nameNode:setString(self.mCurEquip:getName(true))
    local color = Enums.QualityColor[self.mCurEquip.quality]
	if color then
		self.m_EquipInfoNode.nameNode:setTextColor(color)
	end
    --显示孔信息  v.lockedJewelSlot or v.jewelSlots
    for i=1,4 do
        CCNode_setVisible(self.slotNode[i],false)
        self.slotNode[i]:setPosition(self.slotPos[i])
    end

    local jewelSlotNum = #self.mCurEquip.jewelSlots
    if jewelSlotNum==1 then
        --有1孔
        CCNode_setVisible(self.slotNode[2],true)
        self:showSlotNode(self.mCurEquip.jewelSlots[1],self.slotNode[2]:findChild("Panel/icon"),1)
    elseif jewelSlotNum==2 then
        --有2孔
        CCNode_setVisible(self.slotNode[1],true)
        CCNode_setVisible(self.slotNode[3],true)
        self:showSlotNode(self.mCurEquip.jewelSlots[1],self.slotNode[1]:findChild("Panel/icon"),1)
        self:showSlotNode(self.mCurEquip.jewelSlots[2],self.slotNode[3]:findChild("Panel/icon"),2)
    else
        --有3 4孔
        for i=1,jewelSlotNum do
            CCNode_setVisible(self.slotNode[i],true)
            self:showSlotNode(self.mCurEquip.jewelSlots[i],self.slotNode[i]:findChild("Panel/icon"),i)
        end
    end
    --四个孔需要转动
    local offsetX = { 20,82, -20,-82 }
    local offsetY = { -60,45,60,-45}
    
    if jewelSlotNum == 4 then
        for i = 1,jewelSlotNum do
            self.slotNode[i]:setPosition(cc.p(self.slotPos[i].x + offsetX[i],self.slotPos[i].y+ offsetY[i]))
        end
    end
end
--点击装备上 镶嵌的孔
function JewelView:onChooseSlot(slot ,index)
    for i=1,4 do
        CCNode_setVisible(self.slotNode[i]:findChild("Panel/icon/Panel/selected"),false)
    end
    self._curSelectedSlotNodeIcon:findChild("Panel/selected"):setVisible(true)
    self.mCurSlotIndex=index
    self.mCurJewel=jewel
    self:showSlotInfo(slot)
end
--显示孔的信息
function JewelView:showSlotNode(slot,slotNode,index)
    if not slot then
        return
    end
    slotNode:setVisible(true)
    local gradeNode=slotNode:findChild("Panel/grade")
    local iconNode=slotNode:findChild("Panel/icon")
    local selectedNode=slotNode:findChild("Panel/selected")
    local notingTip = slotNode:findChild("Panel/text")
    selectedNode:setVisible(false)
    local node=slotNode:findChild("Panel")

    node:addClickEventListener(function (  )
        self._curSelectedSlotNodeIcon = slotNode
        executeFunc(self._onOperate,"onChooseSlot",{slot = slot ,index = index})
    end)

    local panel_numNode=slotNode:findChild("Panel/Panel_num")
    panel_numNode:setVisible(false)

    local panel_LvNode=slotNode:findChild("Panel/level")
    panel_LvNode:setVisible(false)

    if slot.jewel then
        local jewel = slot.jewel
        gradeNode:loadTexture(jewel:getIconBg())
        iconNode:setVisible(true)
        iconNode:loadTexture(jewel:getIcon())
--        panel_LvNode:setString( "+" .. jewel.lv )
        -- 客户端将宝石等级主动+1
        local templv = tonumber(jewel.lv) + 1
        panel_LvNode:setString(tostring(templv))
        panel_LvNode:setVisible(templv > 0)
        notingTip:setVisible(false)
    else
        --无宝石
        gradeNode:loadTexture(Res.Qulity_Icon_Bg[1])
        iconNode:setVisible(false)
        iconNode:loadTexture( slot:getBigIcon() )
        selectedNode:setVisible(false)
        notingTip:setVisible(true)
    end

    --redpoint     
    if app:sendMsg("JewelModel", "slotHasRedPoint", self.mCurEquip.uid, index) then
        slotNode:findChild("Panel/dot"):show()
    else
        slotNode:findChild("Panel/dot"):hide()
    end

    if self.mCurSlotIndex==index then
        self._curSelectedSlotNodeIcon = slotNode
        executeFunc(self._onOperate,"onChooseSlot",{slot = slot ,index = index})
    end
end

function JewelView:refreshLeftList(listData,selectIndex,slotIndex)
    if #listData <=0 then
        return
    end
    self.equipList = listData
    self:refreshList(listData,selectIndex) 
    self:showEquipInfo(selectIndex,slotIndex)
    --同时刷新一下当前宝石评分
    self.equipNode:findChild("Panel/star_num"):setString(string.format(L("jewel_master_string2"),UD:getCurEquipedJewelScore()))
end

function JewelView:showSlotInfo(slot)
    if nil == slot.slotType or "" == slot.slotType then
        return
    end

    local slotIconBg=nil
    self._CurSlotTips:setString(L("sockettype_0"))

    local bigIcon = slot:getBigIcon()
    if bigIcon then
        self._CurSlotNodeBg:loadTexture( bigIcon )
    end
    self._CurSlotTips:setString( slot:getTypeDesc() )

    local curSlotNode = IconRender.create(self._CurSlotNode)
    curSlotNode:setClickEnable(false)
    local isShowFactor = false
    -- print("#########  showSlotInfo")
    -- dump(slot)
    if slot.jewel then
        isShowFactor = true
        local jewel = slot.jewel
        self.curSlotJewel=jewel
        curSlotNode:setData(jewel)

        local strName = jewel:getName(true)
        -- print("#########  showSlotInfo  strName   ",strName)
        self._CurSlotName:setString(jewel:getName(true))
        local color = Enums.QualityColor[jewel.quality]
	    if color then
		    self._CurSlotName:setTextColor(color)
	    end
        local attrName, attrNum = UD:formatAttr( jewel:getAttrType(), jewel:getAttrVal() )
        self._CurSlotPropNum:setString( table.concat( { attrName, attrNum } ) )
        self._CurSlotButton_unload:setVisible(true)

        if slot.jewel.posShow and slot.jewel.posShow:len() > 1 then
            CCNode_setVisible(self.slotJewelPosTip,false)
            local icons = slot.jewel.posShow:split("/")
            -- dump(icons, "icons::::")
            for i = 1, 6 do
                if icons[i] then
                    self.midEquipSelIcons[i]:show()
                    self.midEquipSelIcons[i]:loadTexture("art/jewel_icon/"..icons[i]..".png")
                else
                    self.midEquipSelIcons[i]:hide()
                end
            end
        else
            for i = 1, 6 do
                self.midEquipSelIcons[i]:hide()
            end
            CCNode_setVisible(self.slotJewelPosTip,true)
            self.slotJewelPosTip:setString(L(slot.jewel.pos))
        end
    else
        self.curSlotJewel = nil
        curSlotNode:setEmptyIcon()
        self._CurSlotButton_unload:setVisible(false)
        CCNode_setVisible(self.slotJewelPosTip,false)
        for i = 1, 6 do
            self.midEquipSelIcons[i]:hide()
        end
    end

    CCNode_setVisible(self._CurSlotNode,isShowFactor)
    CCNode_setVisible(self._CurSlotTips,not isShowFactor)
    CCNode_setVisible(self._CurSlotName,isShowFactor)
    CCNode_setVisible(self._CurSlotPropNum,isShowFactor)

    if self.mCurJewel then
        self:showBagJewelInfo()
    else
        self.bagDetailPanel:setVisible(false)
    end
end

function JewelView:setInlayBtnStatus(fittype, fitlevel)
    self.btnInlay:setVisible(fittype and fitlevel)
    self.btnGotoInlay:setVisible((not fittype ) and fitlevel)
end

function JewelView:showBagJewelInfo()
    if not self.mCurJewel then
        
        return
    end
    self.bagDetailPanel:setVisible(true)
    
    CCNode_setVisible(self.tipRightJewelPos ,true)
    if self.mCurJewel.posShow and self.mCurJewel.posShow:len() > 1 then
        self.tipRightJewelPos:hide()
        local icons = self.mCurJewel.posShow:split("/")
        -- dump(icons, "icons::")
        for i = 1, 6 do
            if icons[i] then
                self.rightBagSelIcons[i]:show()
                self.rightBagSelIcons[i]:loadTexture("art/jewel_icon/"..icons[i]..".png")
            else
                self.rightBagSelIcons[i]:hide()
            end
        end
    else
        for i = 1, 6 do
            self.rightBagSelIcons[i]:hide()
        end
        self.tipRightJewelPos:show()
        self.tipRightJewelPos:setString(L(self.mCurJewel.pos))
    end

    local curJewelNode = IconRender.create(self._CurJewelNode)
    curJewelNode:setData(self.mCurJewel)
    curJewelNode:setClickEnable(false)

    self._CurJewelName:setString(self.mCurJewel:getName(true))
    local color = Enums.QualityColor[self.mCurJewel.quality]
	if color then
		self._CurJewelName:setTextColor(color)
	end

    local attrName, attrNum = UD:formatAttr( self.mCurJewel:getAttrType(), self.mCurJewel:getAttrVal() )
    self._CurJewelPropNum:setString( table.concat( { attrName, attrNum } ) )

    self._CurJewelRecommend:setVisible( false )
    if self.mCurEquip and self.mCurSlotIndex and self.mCurSlotIndex>0 and self.mCurEquip.jewelSlots[self.mCurSlotIndex] then
        local curSlotButton_changeTlt=self.bagDetailPanel:findChild("Button_change/name")
        local isFitLevel = self.mCurJewel:getUseLv()<=UD:getLevel()
        local isFitType  = self.mCurEquip.jewelSlots[self.mCurSlotIndex]:fitJewel(self.mCurJewel)
        self:setInlayBtnStatus(isFitType, isFitLevel)
        if isFitLevel and  isFitType then
            self._CurJewelRecommend:setVisible(self:isRecommend(self.mCurJewel))
            -- self.btnInlay:setVisible(true)
            CCNode_setVisible(self.tipRightJewelType ,false)
            if self.mCurEquip.jewelSlots[self.mCurSlotIndex]:hasJewel() then
                curSlotButton_changeTlt:setString(L("lua_code_text_537"))
            else
                curSlotButton_changeTlt:setString(L("lua_code_text_280"))
            end
        else
            -- curSlotButton_changeTlt:setString(L"jewel_inlay_gotoinlay")
            CCNode_setVisible(self.tipRightJewelType ,true)
            if isFitLevel == false then
                self.tipRightJewelType:setString(L("tips_2000118"))
            elseif isFitType == false then
                self.tipRightJewelType:setString(L("tips_2000281"))
            end
        end
    else
        self.btnInlay:setVisible(false)
    end
end


--刷新装备选中按钮状态
function JewelView:refreshSelectStatus(selectIndex)
    self.equipListView:setFoucsIndex(selectIndex)
end

function JewelView:refreshList(listData,selectIndex)
    self.equipListView:reloadData(listData)
    self.equipListView:setFoucsIndex(selectIndex)
    self.equipListView:scrollToIndex(selectIndex)
end

function JewelView:equipJump( selectIndex )
    if selectIndex == nil  then return end
    self.equipListView:jumpToIndex(selectIndex)
end

--是否推荐
function JewelView:isRecommend( jewel )
    if not self.curSlotJewel then
        return true
    end
    return jewel:getAttrType() == self.curSlotJewel:getAttrType() 
    and  jewel:getGearScore() > self.curSlotJewel:getGearScore()
end


-- 刷新镶嵌panel宝石列表
function JewelView:refreshJewelBagPanel(jewelList)
    if self.lastJewelCount ~= #jewelList then
        self.lastJewelCount = #jewelList
        self.bagScrollView:reloadData(jewelList, {startIndex = 1})
    else
        self.bagScrollView:reloadData(jewelList, {startIndex = 1})
        if checknumber(self.lastIndex) > 0 then
            self.bagScrollView:jumpToIndex(self.lastIndex)
        end
    end
    self:_initBagScrollView()
end

-- 刷新镶嵌UI显示状态
function JewelView:refreshXQUIStatus( hasEquips, hasJewels )
    hasEquips = hasEquips or false
    hasJewels = hasJewels or false
    self.equipBG:setVisible( hasEquips )
    self.m_EquipInfoNode:setVisible( hasEquips )
    self.equipTipNoEquip:setVisible( not hasEquips )

    if hasEquips then -- 有装备？ 
        self.equipRightPanel:setVisible( hasJewels )
        self.equipTipNoJewel:setVisible( not hasJewels )
    else
        self.equipRightPanel:setVisible( false )
        self.equipTipNoJewel:setVisible( false )
    end
    self.blankNode:setVisible(not hasEquips)
    self.equipNode:setVisible(hasEquips)

end
-- 刷新升级UI显示状态
function JewelView:refreshUpgradeUIStatus( hasJewels, hasJewelsCanBeAbsorb )
    hasJewels = hasJewels or false
    self.jewelBG:setVisible( hasJewels )
    self.jewelUpNoEquips:setVisible( not hasJewels )
    self.jewelUpRight:setVisible( hasJewels )
    self.jewelUpNoJewel:setVisible( not hasJewels )
end
-- 播放镶嵌成功动画
function JewelView:playSetJewelSuccessAni()
    local slotNodeTemp = nil
    if self._curSelectedSlotNodeIcon then
        slotNodeTemp = self._curSelectedSlotNodeIcon:getParent():getParent()
    end
    if slotNodeTemp then
        local slotNodePanel = slotNodeTemp:getChildByName( "Panel" )
        local amiNode = slotNodePanel:getChildByName( "amiNodeTemp" )
        if not amiNode then
            amiNode = cc.CSLoader:createNode( Res.EquipStrengthenSuccessAmi )
            amiNode:setName( "amiNodeTemp" )
            amiNode:setPosition( slotNodePanel:getChildByName( "ani" ):getPosition())
            slotNodePanel:addChild( amiNode )
        end
        amiNode:performWithDelay( function()
            amiNode:getTimeline():gotoFrameAndPlay( 0, false )
        end, 0)
    end
end

function JewelView:getAniNode(k)
    self.aniNodes = self.aniNodes or {}
    if cc.isAlive(self.aniNodes[k]) then
        self.aniNodes[k]:removeFromParent()
    end

    local aniNode = cc.CSLoader:createNode( Res.EquipStrengthenSuccessAmi )
    self.aniNodes[k] = aniNode

    return aniNode
end

function JewelView:addAniToNode(k, n)
    local an = self:getAniNode(k)
    
    if cc.isAlive(an) then
        n:addChild(an)
        an:getTimeline():gotoFrameAndPlay( 0, false )

        an:setPosition(cc.p(n:getContentSize().width*0.5, n:getContentSize().height*0.5))
    end
end

function JewelView:addAniToJewel(uid)
    self.jewelScrollView:foreachCellModels(function(cellModel, cellData)
        if cellData.uid == uid then
            self:addAniToNode(uid, cellModel.cell)
            return
        end
    end)
end

function JewelView:_clickRightBagScrollView(renderData)
    if not renderData then
        return
    end
    self.bagScrollView:foreachCellModels(function(cellModel, data)
        if cellModel.cell then
            cellModel.cell:setSelected(renderData.uid == data.uid)
        else
            cellModel:setSelected(renderData.uid == data.uid)
        end
    end)
    self.mCurJewel= renderData
    self:showBagJewelInfo()
end


function JewelView:_initBagScrollView()

    local selectData = nil
    if self.mCurJewel then
        selectData = self.mCurJewel
    -- else
    --     selectData = self.bagScrollView:getDataByIndex(1)
    --     if not selectData then
    --         return
    --     end
    end

    local firstIndex
    local firstRecommendIndex
    self.bagScrollView:foreachCellModels(function(cellModel, jewlData)
        local isMaskVisible = flase
        local isRecommendVisibl = false
        if self.mCurEquip and self.mCurSlotIndex and
            self.mCurSlotIndex > 0 and self.mCurEquip.jewelSlots[self.mCurSlotIndex] then
            if jewlData:getUseLv() <= UD:getLevel() and
                self.mCurEquip.jewelSlots[self.mCurSlotIndex]:fitJewel(jewlData) then
                isMaskVisible = false
                if firstIndex == nil or firstIndex > cellModel.index then
                    firstIndex = cellModel.index
                end
                if selectData == nil then
                    selectData = jewlData
                end
                isRecommendVisibl = self:isRecommend( jewlData)
                if isRecommendVisibl then
                    if firstRecommendIndex == nil or firstRecommendIndex > cellModel.index then
                        firstRecommendIndex = cellModel.index
                    end
                end
            else
                isMaskVisible = true
                isRecommendVisibl = false
            end
        else
            isMaskVisible = false
            isRecommendVisibl = false
        end
        local isSelected = selectData and selectData.uid == jewlData.uid
     
        if cellModel.cell then
            cellModel.cell:setSelected(isSelected)
            cellModel.cell:setMaskVisible(isMaskVisible)
            cellModel.cell:setRecommendVisible(isRecommendVisibl)
        else
            cellModel:setSelected(isSelected)
            cellModel:setUIState("recommend", isRecommendVisibl)
            cellModel:setUIState("mask", isMaskVisible)
        end
    end)

    if firstRecommendIndex and firstRecommendIndex >= 0 then
        self.bagScrollView:scrollToIndex(firstRecommendIndex)
        self.lastIndex = firstRecommendIndex
    elseif firstIndex and firstIndex >= 0 then
        self.bagScrollView:scrollToIndex(firstIndex)
        self.lastIndex = firstIndex
    end   
    
    self.mCurJewel = selectData
    self:showBagJewelInfo()
end


return JewelView
